 <?php
class SqlServerAll{
	
	private $connect = array();
	
	public function __construct($ip,$user,$pass,$database){
		
		$this->connect = array(
			'ip' => $ip,						// sqlServer数据库服务器ip
			'user' => $user,					// 数据库登录用户名 
			'pass' => $pass,					// 数据库登录用户密码 
			'database' => $database,			// 数据库名 
		);
	}
	//sqlServer数据库连接
	public function SqlServerConnection(){
		
		$connectionInfo = array("UID"=>$this->connect['user'], "PWD"=>$this->connect['pass'], "Database"=>$this->connect['database']);
		
		$SqlLink = sqlsrv_connect($this->connect['ip'], $connectionInfo);		

		if($SqlLink == false){
			 //print_r( sqlsrv_errors());die;//异常详情
			return false;
		}
		return $SqlLink;
	}
	public function  close($conn){
		 sqlsrv_close($conn);
	}
	
	/*sqlserver输出查询结果
	*$sqlserverCon			sqlserver数据库连接资源
	*$sql					要运行的sql
	*返回值解释：		
	$status = array(
		is_succeed			sql是否执行成功
		rows_affected		受影响行数
		is_null				执行结果是否为空
		list				执行结果
	)
	*/
	public function sqlserverQuery($sqlserverCon,$sql){

		$list = sqlsrv_query($sqlserverCon,$sql);
		
		if(!$list){
			$status['is_succeed'] = '0';
			return $status;
		}else{
			$status['is_succeed'] = '1';
			$status['rows_affected'] = sqlsrv_rows_affected($list);
		}
		$sqlList = array();
		while($res=sqlsrv_fetch_object($list)){
			$data[] = $this->objectToArray($res);
		}
		//检测查询结果是否为空
		if(!empty($data)){
			$status['list'] = $data;
			$status['is_null'] = '1';
		}else{
			$status['is_null'] = '0';
		}
		return $status;
	}
	//递归将sql查询结果对象转化为数组
	private function objectToArray($row){
		$arr = is_object($row) ? get_object_vars($row) : $row;		
		if(is_array($arr)){
			foreach($arr as $key=>$value){
				if(is_object($value)){ 
					$data[$key] = $this->objectToArray($value);
				}else{
					$data[$key] = $value;
				}
			}
			return $data;
		}else{
			return $arr;
		}
		return $arr;
	}
	/*拼接数组插入数据库sql
	*返回值说明：
	$insert = array(
		fields			字段名
		list			值
	)
	*/
	private function insertSql($arr){
		$insert = array();
		$insert['list'] = "'".implode("','", array_values($arr))."'";
		$insert['fields'] = implode(",", array_keys($arr));
		return $insert;
	}
}
    
?>